import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      // 存入vuex
      state.token = token
      // 存入cookie
      setToken(token)
    },
    // 存入用户信息
    setUserInfo(state, data) {
      state.userInfo = data
    },
    // 清空用户信息，token，
    // 同步删除cookie里面的token
    removeUserInfo(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  },
  actions: {
    async fetchLogin(store, data) {
      const res = await login(data)
      store.commit('setToken', res)
    },
    async fetchUserInfo(store) {
      const res = await getUserInfo()
      const res_ = await getUserDetailById(res.userId)
      store.commit('setUserInfo', { ...res, ...res_ })

      // 将获取的用户信息结果return，可以在调用这个函数的时候得到返回数据
      return res
    }
  }
}
